"use client";

import { useState } from "react";
import { Button, Card, Table, Tag, Space, App } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { api } from "~/trpc/react";
import { type Task } from "@prisma/client";
import { TaskForm } from "./TaskForm";
import { useRouter } from "next/navigation";

interface TaskListProps {
  courseId: string;
}

export function TaskList({ courseId }: TaskListProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const { message, modal } = App.useApp();
  const router = useRouter();

  const { data, isLoading, refetch } = api.tasks.list.useQuery({
    courseId,
    page: currentPage,
    pageSize,
  });

  const deleteMutation = api.tasks.delete.useMutation({
    onSuccess: async () => {
      message.success("任务删除成功");
      await refetch();
    },
    onError: (error) => {
      message.error(error.message || "删除失败，请重试");
    },
  });

  const handleEdit = (task: Task) => {
    setEditingTask(task);
    setIsModalOpen(true);
  };

  const handleDelete = async (task: Task) => {
    try {
      const confirmed = await modal.confirm({
        title: "确认删除",
        content: "确定要删除这个任务吗？此操作不可恢复。",
        okText: "确认",
        cancelText: "取消",
        okButtonProps: {
          danger: true,
        },
      });

      if (confirmed) {
        await deleteMutation.mutateAsync(task.id);
      }
    } catch (error) {
      if (error instanceof Error) {
        console.error("删除任务时出错:", error);
      }
    }
  };

  const handleModalClose = () => {
    setIsModalOpen(false);
    setEditingTask(null);
  };

  const getStatusTag = (status: string) => {
    const statusConfig = {
      NOT_STARTED: { color: 'default', text: '未开始' },
      IN_PROGRESS: { color: 'processing', text: '进行中' },
      COMPLETED: { color: 'success', text: '已完成' },
    };

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.NOT_STARTED;
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const columns = [
    {
      title: "任务标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "优先级",
      dataIndex: "priority",
      key: "priority",
      render: (priority: Task["priority"]) => (
        <Tag color={
          priority === "HIGH" ? "red" :
          priority === "MEDIUM" ? "orange" : "green"
        }>
          {
            priority === "HIGH" ? "高" :
            priority === "MEDIUM" ? "中" : "低"
          }
        </Tag>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: Task["status"]) => getStatusTag(status),
    },
    {
      title: "截止日期",
      dataIndex: "dueDate",
      key: "dueDate",
      render: (date: Date | null) => date ? new Date(date).toLocaleDateString() : "-",
    },
    {
      title: "操作",
      key: "action",
      render: (_: unknown, record: Task) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button 
            type="link" 
            onClick={() => router.push(`/courses/${courseId}/tasks/${record.id}`)}
          >
            查看步骤
          </Button>
          <Button
            type="link"
            danger
            onClick={() => handleDelete(record)}
            loading={deleteMutation.isLoading}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Card
      title="任务管理"
      extra={
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setIsModalOpen(true)}
        >
          新建任务
        </Button>
      }
    >
      <Table
        columns={columns}
        dataSource={data?.items}
        rowKey="id"
        loading={isLoading || deleteMutation.isLoading}
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: data?.total,
          onChange: (page, size) => {
            setCurrentPage(page);
            setPageSize(size);
          },
        }}
      />

      <TaskForm
        courseId={courseId}
        open={isModalOpen}
        initialValues={editingTask || undefined}
        onCancel={handleModalClose}
        onSuccess={async () => {
          handleModalClose();
          await refetch();
        }}
      />
    </Card>
  );
} 